<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>xml文件解析</title>
	<script type="text/javascript">
		window.onload = function(){
			var btn = document.getElementById('btn');
			btn.onclick = function(){
				showBookInfo();
			}
			function showBookInfo(){
				document.getElementById('bookInfo').innerHTML = '';
				var xhr = null;
				if(window.XMLHttpRequest){
					xhr = new XMLHttpRequest();
				}else{
					xhr = new ActiveXObject('Microsoft.XMLHTTP');
				}
				console.log('第一步'+xhr.readyState);
				xhr.open('get','data.xml');
				console.log('第二步'+xhr.readyState);
				xhr.send(null);
				xhr.onreadystatechange = function(){
					if(xhr.readyState == 4 && xhr.status == 200){
						var data = xhr.responseXML;   //返回文档的全部内容   xml 对象
						var bs = data.getElementsByTagName('bookstore')[0];  //获得bookstore里的内容
						console.log(bs);
						var books = bs.getElementsByTagName('book');  // 获得book标签里的内容 
						var tag = '';
						for(var i=0; i<books.length; i++){   //循环输出book标签了的内容
							var book = books[i];
							var name = book.getElementsByTagName('name')[0];   //获得相应的节点
							var category = book.getElementsByTagName('category')[0];
							var desc = book.getElementsByTagName('desc')[0];
							tag += '<tr><td>'+getNodeText(name)+'</td><td>'+getNodeText(category)+'</td><td>'+getNodeText(desc)+'</td></tr>';
						}
						var tbody = document.createElement('tbody');
						tbody.innerHTML = tag;
						document.getElementById('bookInfo').appendChild(tbody);
					}
				}
			}
		}
		//获取文本节点里的内容
		function getNodeText(node){
			if(window.ActiveXObject){
				return node.text;
			}else{
				if(node.nodeType == 1){
					return node.textContent;
				}
			}
		}
	</script>
</head>
<body>
	<input type="button" value="点击" id="btn">
	<div>
		<table id="bookInfo"></table>
	</div>

</body>
</html>